package com.longrise.android.loaddata.newloaddata;

import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.google.gson.Gson;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.LEAP.Base.Objects.ResultSetMetaData;
import com.longrise.android.loaddata.ObserverCallBack;
import com.longrise.android.loaddata.cookie.CookiesManager;
import com.longrise.android.util.IntenetUtil;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.R.attr.data;

/**
 * Created by chengsan on 16/5/20.
 */
public class LoadDataManager4 extends LoadDataManagerFather {
    private static LoadDataManager4 loadDataManager4 = null;
    private Gson mGson;

    public static LoadDataManager4 getInstance(Context context) {
        if (null == loadDataManager4) {
            synchronized (LoadDataManager4.class) {
                loadDataManager4 = new LoadDataManager4(context.getApplicationContext());
            }
        }
        return loadDataManager4;
    }

    public static LoadDataManager4 getInstance() {
        if (null == loadDataManager4) {
            synchronized (LoadDataManager4.class) {
                loadDataManager4 = new LoadDataManager4();
            }
        }
        return loadDataManager4;
    }

    public LoadDataManager4() {
        super();
    }

    public LoadDataManager4(Context context) {
        super(context);
        this.context = context;
    }

    /**
     * 增加用gson 解析 xkj 20171129
     */
    private Gson getGson(){
        if(mGson == null){
            mGson = new Gson();
        }
        return mGson;
    }

    /**
     * 请求服务
     *
     * @param key                       用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl                服务的URL
     * @param serviceName               服务名
     * @param bean                      参数
     * @param onRequestCompleteListener 请求完成回调接口
     */
    public void callService(String key, String serviceUrl, String serviceName,
                            EntityBean bean, OnRequestCompleteListener onRequestCompleteListener) {
        callServiceWithFile2(1, key, serviceUrl, serviceName, bean, false, null, null, null,
                null, null, onRequestCompleteListener);
    }

    /**
     * 请求服务,可以设置缓存
     *
     * @param key                       用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl                服务的URL
     * @param serviceName               服务名
     * @param bean                      参数
     * @param openCache                 开启缓存
     * @param onRequestCompleteListener 请求完成回调接口
     */
    public void callService2(String key, String serviceUrl, String serviceName,
                             EntityBean bean, boolean openCache, OnRequestCompleteListener
                                     onRequestCompleteListener) {
        callServiceWithFile2(1, key, serviceUrl, serviceName, bean, openCache,
                null, null, null, null, null, onRequestCompleteListener);
    }


    /**
     * 请求服务，该服务可以同时上传文件
     *
     * @param key                       用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl                服务的URL
     * @param serviceName               服务名
     * @param bean                      参数
     * @param openCache                 开启缓存
     * @param fileKey                   文件对应的Key
     * @param file                      需要上传的File文件对象
     * @param mimeType                  文件类型，如："image/pjpeg"
     * @param onRequestCompleteListener 请求完成回调接口
     */
    public void callService3(String key, String serviceUrl, String serviceName,
                             EntityBean bean, boolean openCache, String fileKey, File file, String mimeType,
                             OnuploadFileLishtener onuploadFileLishtener,
                             OnRequestCompleteListener onRequestCompleteListener) {
        callServiceWithFile2(2, key, serviceUrl, serviceName, bean, openCache, fileKey, file, mimeType, null,
                onuploadFileLishtener, onRequestCompleteListener);
    }

    /**
     * 请求服务,可以设置缓存和请求头数据
     *
     * @param key                       用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl                服务的URL
     * @param serviceName               服务名
     * @param bean                      参数
     * @param openCache                 是否开启缓存
     * @param headMap                   设置请求头的数据
     * @param onRequestCompleteListener 请求完成回调接口
     */
    public void callService4(String key, String serviceUrl, String serviceName,
                             EntityBean bean, boolean openCache, Map headMap,
                             OnRequestCompleteListener onRequestCompleteListener) {
        callServiceWithFile2(1, key, serviceUrl, serviceName, bean, openCache,
                null, null, null, headMap, null, onRequestCompleteListener);
    }

    /**
     * 请求服务，该服务可以同时上传文件和设置请求头数据
     *
     * @param key                       用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl                服务的URL
     * @param serviceName               服务名
     * @param bean                      参数
     * @param openCache                 开启缓存
     * @param headMap                   设置请求头的数据
     * @param fileKey                   文件对应的Key
     * @param file                      需要上传的File文件对象
     * @param mimeType                  文件类型，如："image/pjpeg"
     * @param onRequestCompleteListener 请求完成回调接口
     */
    public void callService5(String key, String serviceUrl, String serviceName,
                             EntityBean bean, boolean openCache, Map headMap, String fileKey,
                             File file, String mimeType, OnuploadFileLishtener onuploadFileLishtener,
                             OnRequestCompleteListener onRequestCompleteListener) {
        callServiceWithFile2(2, key, serviceUrl, serviceName, bean, openCache, fileKey, file, mimeType, headMap,
                onuploadFileLishtener, onRequestCompleteListener);
    }


    /**
     * 请求服务，该服务可以上传文件
     *
     * @param type                      类型
     *                                  1:不带文件
     *                                  2、请求中带文件
     * @param key                       用于取消请求使用，请用该类中的getKey()方法来生成
     * @param serviceUrl                服务的URL
     * @param serviceName               服务名
     * @param requestBean                      参数
     * @param openCache                 开启缓存
     * @param fileKey                   文件对应的Key
     * @param file                      需要上传的File文件对象
     * @param mimeType                  文件类型，如："image/pjpeg"
     * @param onRequestCompleteListener 请求完成回调接口
     */
    private void callServiceWithFile2(final int type, final String key, final String serviceUrl, final String serviceName,
                                      final EntityBean requestBean, final boolean openCache, final String fileKey, final File file,
                                      final String mimeType, final Map headMap,
                                      final OnuploadFileLishtener onuploadFileLishtener,
                                      final OnRequestCompleteListener onRequestCompleteListener) {
        if (null != context) {
            if (IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_NONE) {
                if (null != onRequestCompleteListener) {
                    onRequestCompleteListener.onError(key, serviceName, ResultType.NoNetWorks);
                    onRequestCompleteListener.onFinished(key, serviceName);
                }
                if (this.showNetNotice) {
                    Toast.makeText(context, "没有网络连接", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }

        MultipartBody.Builder builderFile = null;
        FormBody.Builder builder = null;
        if (type == 1 || type == 3) {
            builder = new FormBody.Builder();
        } else if (type == 2 || type == 4) {
            builderFile = new MultipartBody.Builder().setType(MultipartBody.FORM);

        }

        if (requestBean != null) {
            ResultSetMetaData[] keys = requestBean.toResultSet().getMetaData();
            if (null != keys) {
                for (int i = 0; i < keys.length; i++) {
                    String beanKey = keys[i].getName();
                    String value = null;
                    Object object = requestBean.get(beanKey);
                    //将所有的类型全部转换成String类型
                    if (object != null) {
                        if ((object instanceof String)) {
                            value = object.toString();
                        } else if ((object instanceof Integer)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof Long)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof Number)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof Boolean)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof BigDecimal)) {
                            value = String.valueOf(object);
                        } else {
                            //value = JSONSerializer.getInstance().Serialize(object);
                            value =  getGson().toJson(object);
                        }
                    }

                    if (null == value) {
                        value = "";
                    }
                    if (type == 1 || type == 3) {
                        builder.add(beanKey, value);
                    } else if (type == 2 || type == 4) {

                        builderFile.addFormDataPart(beanKey, value);
                    }
                }
            }
        }

        //处理请求头数据
        Headers.Builder tempBuild = new Headers.Builder();
        if (headMap != null) {
            Set<String> tempSet = headMap.keySet();
            if (null != tempSet) {
                for (String tempKey : tempSet) {
                    Object tempobj = headMap.get(tempKey);
                    if (null != tempobj && tempobj instanceof String)
                        tempBuild.add(tempKey, (String) tempobj);
                }
            }
        }

        //添加上传进度回调
        Request request = null;
        if (type == 1 || type == 3) {
            request = new Request.Builder().url(serviceUrl + "/" + serviceName + "/query")
                    .headers(tempBuild.build())
                    .post(builder.build()).build();
        } else if (type == 2 || type == 4) {
            if (null != file && file.exists()) {
                //添加文件
                builderFile.addFormDataPart(fileKey, file.getName(),
                        RequestBody.create(MediaType.parse(mimeType), file));

                //添加上传进度回调
                request = new Request.Builder().url(serviceUrl + "/" + serviceName + "/query")
                        .headers(tempBuild.build())
                        .post(new LongriseRequestBody(builderFile.build()) {

                            @Override
                            public void loading(long current, long total, boolean done) {
                                if (null != onuploadFileLishtener) {
                                    onuploadFileLishtener.onUpload(current, total);
                                }
                            }
                        }).build();
            }
        }

        //设置超时时间
        OkHttpClient okHttpClient = null;
        if (null != cerName && !cerName.isEmpty()) {
            //设置所有证书都信任，不用传证书进来
            //X509TrustManager trustManager = new TrustAllManager();
            SSLSocketFactory sslSocketFactory;
            X509TrustManager trustManager;

            try {
                //设置对应的证书信任
                trustManager = trustManagerForCertificates(context.getAssets().open(cerName));
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
                sslSocketFactory = sslContext.getSocketFactory();

                okHttpClient = new OkHttpClient.Builder()
                        .sslSocketFactory(sslSocketFactory, trustManager)
                        .hostnameVerifier(new TrustAllHostnameVerifier())
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .cookieJar(cookiesManager)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();

                onRequestCompleteListener.onError(key, serviceName, ResultType.NoNetWorks);
                onRequestCompleteListener.onFinished(key, serviceName);
            }
        } else {
            //设置超时时间
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .cookieJar(cookiesManager)
                    .build();
        }

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            if (onRequestCompleteListener != null) {
                                onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                onRequestCompleteListener.onFinished(key, serviceName);
                            }
                        }
                    });
                }
            }


            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                //序列化成Bean对象
                final EntityBean bean = (EntityBean) JSONSerializer.getInstance().DeSerialize(response.body().string(), EntityBean.class);
                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            if (bean == null) {
                                if (onRequestCompleteListener != null) {
                                    onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                    onRequestCompleteListener.onFinished(key, serviceName);
                                }
                                return;
                            } else {
                                String restate = null;
                                restate = bean.getString(restateKey);
                                if (null == restate || restate.isEmpty()) {
                                    //重新登录超过三次直接返回失败
                                    count = 0;
                                    if (onRequestCompleteListener != null) {
                                        onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                    }

                                    if (null != onRequestCompleteListener) {
                                        onRequestCompleteListener.onFinished(key, serviceName);
                                    }

                                    return;
                                }
                                String[] tempLoginOutArray = null;
                                tempLoginOutArray = loginOutArray;
                                //=====================校验用户是否被挤掉了======================
                                if (tempLoginOutArray != null && tempLoginOutArray.length > 0) {
                                    for (int i = 0; i < tempLoginOutArray.length; i++) {
                                        if (restate.equals(tempLoginOutArray[i])) {
                                            Intent intent = new Intent(LoginOutIntentAction);
                                            intent.putExtra(DataKey, data);
                                            if (null != context) {
                                                intent.putExtra(PageNameKey, context.getPackageName());
                                                context.sendBroadcast(intent);
                                            }


                                            if (onRequestCompleteListener != null) {
                                                onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                            }

                                            if (null != onRequestCompleteListener) {
                                                onRequestCompleteListener.onFinished(key, serviceName);
                                            }

                                            return;
                                        }
                                    }
                                }


                                String[] tempSessionTimeOutArray = null;
                                tempSessionTimeOutArray = sessionTimeOutArray;
                                //===================用户超时==================
                                if (tempSessionTimeOutArray != null && tempSessionTimeOutArray.length > 0) {
                                    for (int i = 0; i < tempSessionTimeOutArray.length; i++) {
                                        if (restate.equals(tempSessionTimeOutArray[i])) {
                                            count++;
                                            if (count > 3) {
                                                //发送广播
                                                Intent intent = new Intent(SessionUnavailIntentAction);
                                                intent.putExtra(DataKey, "");
                                                if (null != context) {
                                                    intent.putExtra(PageNameKey, context.getPackageName());
                                                    context.sendBroadcast(intent);
                                                }

                                                //重新登录超过三次直接返回失败
                                                count = 0;
                                                if (onRequestCompleteListener != null) {
                                                    onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                                }

                                                if (null != onRequestCompleteListener) {
                                                    onRequestCompleteListener.onFinished(key, serviceName);
                                                }

                                                return;
                                            } else {
                                                //重新登录
                                                getCookIdService2(type, key, serviceUrl, serviceName, requestBean,
                                                        openCache, fileKey, file, mimeType, headMap, onuploadFileLishtener,
                                                        onRequestCompleteListener);

                                                return;
                                            }
                                        }
                                    }
                                }


                                if (onRequestCompleteListener != null) {
                                    onRequestCompleteListener.onSuccess(key, serviceName, bean);
                                    onRequestCompleteListener.onFinished(key, serviceName);
                                }
                            }

                        }
                    });
                }
            }
        });
    }


    /**
     * 重新登录2
     *
     * @param key
     * @param serviceUrl
     * @param serviceName
     * @param tempEntityBean
     * @param onRequestCompleteListener
     */
    private void getCookIdService2(final int type, final String key, final String serviceUrl, final String serviceName,
                                   final EntityBean tempEntityBean, final boolean openCache, final String fileKey, final File file,
                                   final String mimeType, final Map headMap, final OnuploadFileLishtener onuploadFileLishtener,
                                   final OnRequestCompleteListener onRequestCompleteListener) {
        EntityBean tempLoginInfoBean = null;
        tempLoginInfoBean = this.loginInfoBean;
        if (tempLoginInfoBean == null) {
            //回调接口
            if (null != onRequestCompleteListener) {
                onRequestCompleteListener.onError(key, serviceName, ResultType.Failure);
                onRequestCompleteListener.onFinished(key, serviceName);
            }
            return;
        }

        FormBody.Builder builder = new FormBody.Builder();

        ResultSetMetaData[] keys = null;
        EntityBean tempBean = tempLoginInfoBean.getBean(PARAMBEAN_KEY_NAME);
        if (null != tempBean) {

            keys = tempBean.toResultSet().getMetaData();
        }
        if (null != keys) {
            for (int i = 0; i < keys.length; i++) {
                String beanKey = keys[i].getName();
                String value = null;
                Object object = tempBean.get(beanKey);
                //将所有的类型全部转换成String类型
                if (object != null) {
                    if ((object instanceof String)) {
                        value = object.toString();
                    } else if ((object instanceof Integer)) {
                        value = String.valueOf(object);
                    } else if ((object instanceof Long)) {
                        value = String.valueOf(object);
                    } else if ((object instanceof Number)) {
                        value = String.valueOf(object);
                    } else if ((object instanceof Boolean)) {
                        value = String.valueOf(object);
                    } else if ((object instanceof BigDecimal)) {
                        value = String.valueOf(object);
                    } else {
                        value = JSONSerializer.getInstance().Serialize(object);
                    }
                }

                if (value == null) {
                    value = "";
                }
                builder.add(beanKey, value);
            }
        }

        //处理请求头数据
        Headers.Builder tempBuild = new Headers.Builder();
        if(headMap != null)
        {
            Set<String> tempSet = headMap.keySet();
            if(null != tempSet)
            {
                for (String tempKey : tempSet)
                {
                    Object tempobj = headMap.get(tempKey);
                    if(null != tempobj && tempobj instanceof String)
                        tempBuild.add(tempKey,(String) tempobj);
                }
            }
        }

        //添加上传进度回调
        Request.Builder request = new Request.Builder().url(tempLoginInfoBean.getString(LoadDataManagerFather.IP_KEY_NAME) + "/" +
                tempLoginInfoBean.getString(LoadDataManagerFather.SERVICENAME_KEY_NAME) + "/query")
                .headers(tempBuild.build())
                .post(builder.build());

        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();

        //设置超时时间
        OkHttpClient okHttpClient = null;
        if (null != cerName && !cerName.isEmpty()) {
            //设置所有证书都信任，不用传证书进来
            //X509TrustManager trustManager = new TrustAllManager();
            SSLSocketFactory sslSocketFactory;
            X509TrustManager trustManager;

            try {
                //设置对应的证书信任
                trustManager = trustManagerForCertificates(context.getAssets().open(cerName));
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, new TrustManager[]{trustManager}, new SecureRandom());
                sslSocketFactory = sslContext.getSocketFactory();

                okHttpClient = new OkHttpClient.Builder()
                        .sslSocketFactory(sslSocketFactory, trustManager)
                        .hostnameVerifier(new TrustAllHostnameVerifier())
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .build();
            } catch (Exception e) {
                e.printStackTrace();

                onRequestCompleteListener.onError(key, serviceName, ResultType.NoNetWorks);
                onRequestCompleteListener.onFinished(key, serviceName);
            }
        } else {
            //设置超时时间
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();
        }


        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            //重新登录失败直接告诉外面需要重新登录
                            Intent intent = new Intent(LoginOutIntentAction);
                            intent.putExtra(DataKey, data);
                            if (null != context)

                            {
                                intent.putExtra(PageNameKey, context.getPackageName());
                                context.sendBroadcast(intent);
                            }
                            if (onRequestCompleteListener != null) {
                                onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                onRequestCompleteListener.onFinished(key, serviceName);
                            }
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                //序列化成Bean对象
                final EntityBean loginAgainBean = (EntityBean) JSONSerializer.getInstance().DeSerialize(response.body().string(), EntityBean.class);

                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            if (null != loginAgainBean) {
                                if (loginAgainClassFullPath != null && !loginAgainClassFullPath.isEmpty()) {
                                    Class<?> c = null;
                                    Constructor constructor = null;
                                    try {
                                        c = Class.forName(loginAgainClassFullPath);
                                        if (c != null) {
                                            constructor = c.getConstructor();
                                            LoadDataUtil loadDataUtil = (LoadDataUtil) constructor.newInstance();
                                            if (null != loadDataUtil) {
                                                //判断是否登录成功
                                                loadDataUtil.loginFinish(loginAgainBean, type, key, serviceUrl, serviceName, tempEntityBean, openCache, fileKey,
                                                        file, mimeType, headMap, onuploadFileLishtener, onRequestCompleteListener);
                                                return;
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        constructor = null;
                                    }

                                }
                            }

                            //重新登录失败直接告诉外面需要重新登录
                            Intent intent = new Intent(LoginOutIntentAction);
                            intent.putExtra(DataKey, data);
                            if (null != context) {
                                intent.putExtra(PageNameKey, context.getPackageName());
                                context.sendBroadcast(intent);
                            }
                            if (onRequestCompleteListener != null) {
                                onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                onRequestCompleteListener.onFinished(key, serviceName);
                            }
                        }
                    });
                }
            }
        });
    }


    /**
     * 取消某个请求
     *
     * @param key
     */
    public void cancelRequest(String key) {
        if (null == key || key.isEmpty()) {
            return;
        }
        if (httpRunnableHashMap != null) {
            Iterator iterator = httpRunnableHashMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String tempKey = (String) entry.getKey();
                if (key.equals(tempKey)) {
                    HttpRunnableFather httpRunnable = httpRunnableHashMap.get(tempKey);
                    ThreadPool.remove(httpRunnable);
                    break;
                }
            }
        }
    }

    /**
     * 获取版本信息
     *
     * @param serviceUrl
     * @param serviceName
     * @param bean
     * @param onRequestCompleteListener
     */
    public void getVersion(String serviceUrl, final String serviceName,
                           EntityBean bean, final OnRequestCompleteListener onRequestCompleteListener) {
        if (null != context) {
            if (IntenetUtil.getNetworkState(context) == IntenetUtil.NETWORN_NONE) {
                if (null != onRequestCompleteListener) {
                    onRequestCompleteListener.onError(null, serviceName, ResultType.NoNetWorks);
                    onRequestCompleteListener.onFinished(null, serviceName);
                }
                if (this.showNetNotice) {
                    Toast.makeText(context, "没有网络连接", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }

        FormBody.Builder builder = new FormBody.Builder();
        if (bean != null) {
            ResultSetMetaData[] keys = bean.toResultSet().getMetaData();
            if (null != keys) {
                for (int i = 0; i < keys.length; i++) {
                    String beanKey = keys[i].getName();
                    String value = null;
                    Object object = bean.get(beanKey);
                    //将所有的类型全部转换成String类型
                    if (object != null) {
                        if ((object instanceof String)) {
                            value = object.toString();
                        } else if ((object instanceof Integer)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof Long)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof Number)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof Boolean)) {
                            value = String.valueOf(object);
                        } else if ((object instanceof BigDecimal)) {
                            value = String.valueOf(object);
                        } else {
                            value = JSONSerializer.getInstance().Serialize(object);
                        }
                    }

                    if (null == value) {
                        value = "";
                    }
                    builder.add(beanKey, value);
                }
            }
        }

        //添加上传进度回调
        Request request = new Request.Builder().url(serviceUrl + "/" + serviceName + "/query")
                .post(builder.build()).build();


        OkHttpClient okHttpClient = new OkHttpClient();
        //设置超时时间
        okHttpClient.newBuilder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            if (onRequestCompleteListener != null) {
                                onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                onRequestCompleteListener.onFinished(null, serviceName);
                            }
                        }
                    });
                }
            }


            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //序列化成Bean对象
                final EntityBean bean = (EntityBean) JSONSerializer.getInstance().DeSerialize(response.body().string(), EntityBean.class);
                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {

                            if (bean == null) {
                                if (onRequestCompleteListener != null) {
                                    onRequestCompleteListener.onError(null, serviceName, ResultType.Failure);
                                    onRequestCompleteListener.onFinished(null, serviceName);
                                }
                            } else {
                                if (onRequestCompleteListener != null) {
                                    onRequestCompleteListener.onSuccess(null, serviceName, bean);
                                    onRequestCompleteListener.onFinished(null, serviceName);
                                }
                            }

                        }
                    });
                }
            }
        });
    }

    /**
     * 获取Key
     *
     * @return
     */
    public String getKey() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取cookie值
     *
     * @return
     */
    public String getCookieString() {
        if (null == cookiesManager) {
            cookiesManager = new CookiesManager(context);
        }

        return cookiesManager.getCookieString();
    }

    /**
     * 添加cookie
     */
    public void addCookie(HttpUrl url, Cookie cookie, String cookieString) {
        if (null == cookiesManager) {
            cookiesManager = new CookiesManager(context);
        }
        cookiesManager.addCookie(url, cookie, cookieString);
    }
}
